﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using Rung.Net.Base;
using Rung.Net.Events;
using Rung.Net.Enums;

namespace Rung.Net.Cache
{
    public class CacheServer : NetBaseServer<byte[]>
    {
        /// <summary>
        /// 传输进度更改事件。
        /// </summary>
        public event CacheProcessChangedServerEventHandler OnCacheProcessChangedServer;

        private bool needFeedbackPackageReceived;
        public bool NeedFeedbackPackageReceived
        {
            get { return needFeedbackPackageReceived; }
            set
            {
                this.needFeedbackPackageReceived = value;

                if (value)
                {
                    this.OnCacheProcessChangedServer += new CacheProcessChangedServerEventHandler(CacheServer_OnCacheProcessChangedServer);
                }
                else
                {
                    this.OnCacheProcessChangedServer -= new CacheProcessChangedServerEventHandler(CacheServer_OnCacheProcessChangedServer);
                }
            }
        }

        void CacheServer_OnCacheProcessChangedServer(object sender, CacheProcessChangedServerEventArgs e)
        {
            // 每个【Cache_CachePackageReceived】包头包括【数据包类型】【总包数】【包索引】【已接收包数】四个 int 值
            byte[] data = new byte[CacheStream.IntLength * 4];
            NetUtility.BlockCopy(BitConverter.GetBytes(MessageTypeBase.Cache_CachePackageReceived), data, 0);
            NetUtility.BlockCopy(BitConverter.GetBytes(e.PackageCountTotal), data, CacheStream.IntLength);
            NetUtility.BlockCopy(BitConverter.GetBytes(e.Index), data, CacheStream.IntLength * 2);
            NetUtility.BlockCopy(BitConverter.GetBytes(e.PackageCountReceived), data, CacheStream.IntLength * 3);

            CacheServerStream stream = this.Clients[e.ClientId].Stream as CacheServerStream;
            stream.SendBytes(data);
        }

        protected override NetBaseStream<byte[]> CreateStream(NetworkStream ns, EndPoint ep)
        {
            CacheServerStream s = new CacheServerStream(ns, ep);

            if (this.OnCacheProcessChangedServer != null)
                s.OnCacheProcessChangedServer += this.OnCacheProcessChangedServer;

            return s;
        }
    }
}
